package com.red.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.red.context.BaseContext;
import com.red.dto.HomePageQueryDTO;
import com.red.entity.Questions;
import com.red.exception.BaseException;
import com.red.mapper.QuestionsMapper;
import com.red.result.PageResult;
import com.red.service.QuestionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Questions> implements QuestionsService {
    @Autowired
    private QuestionsMapper questionsMapper;

    /**
     * 随机查询10个题目
     * @return
     */
    public List<Questions> get_10_question() {

        List<Questions> questionsList = questionsMapper.selectList(new QueryWrapper<>());

        ArrayList<Questions> result = new ArrayList<>();
        //题图总数
        int size = questionsList.size();
        if (size<10){
            new BaseException("题库题目不够");
        }
        Random random = new Random();
        //随机挑选10个题目
        for (int i = 0; i < 10; i++) {
            size = questionsList.size();

            int r = random.nextInt(size);
            //随机挑选一个题添加到集合中
            result.add(questionsList.get(r));
            //删除了这道题 避免出现重复题
            questionsList.remove(r);
        }
        return result;
    }

    /**
     * 新增题目
     * @param questions
     */
    public void insertQuestion(Questions questions) {
        questionsMapper.insert(questions);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteByIds(List<Long> ids) {
        questionsMapper.deleteByIds(ids);
    }

    /**
     * 分页查询
     * @return
     */
    public PageResult pageQuery(HomePageQueryDTO dto) {

        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Questions> page = questionsMapper.pageQuery(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 更改题目
     * @param questions
     */
    public void updateQuestions(Questions questions) {
        questionsMapper.updateById(questions);
    }
}
